cmake_minimum_required(VERSION 3.5)

# Compiler settings (keep your existing paths)
set(CMAKE_C_COMPILER "D:/qt/gcc/mingw-64/bin/gcc.exe")
set(CMAKE_CXX_COMPILER "D:/qt/gcc/mingw-64/bin/g++.exe")

project(QuickJSTest LANGUAGES C CXX)

# C++ configuration
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS ON)

# C configuration
set(CMAKE_C_STANDARD 17)
set(CMAKE_C_STANDARD_REQUIRED ON)
set(CMAKE_C_EXTENSIONS ON)  # Enable GNU extensions

# Find Threads (pthread) package
find_package(Threads REQUIRED)

# Set QuickJS path
set(QUICKJS_DIR "${CMAKE_SOURCE_DIR}/quickjs" CACHE PATH "Path to QuickJS source")
message(STATUS "QuickJS directory: ${QUICKJS_DIR}")
message(STATUS "Build type: ${CMAKE_BUILD_TYPE}")

# Verify QuickJS source files
set(QUICKJS_SOURCES
    "${QUICKJS_DIR}/quickjs.c"
    "${QUICKJS_DIR}/libunicode.c"
    "${QUICKJS_DIR}/cutils.c"
    "${QUICKJS_DIR}/libregexp.c"
)

foreach(source_file IN LISTS QUICKJS_SOURCES)
    if(NOT EXISTS "${source_file}")
        message(FATAL_ERROR "QuickJS source file not found: ${source_file}")
    endif()
endforeach()

# Main executable
add_executable(QuickJSTest main.cpp ${QUICKJS_SOURCES})

# Include directories
target_include_directories(QuickJSTest PRIVATE ${QUICKJS_DIR})

# MinGW specific settings
if(MINGW)
    target_compile_definitions(QuickJSTest PRIVATE
        _GNU_SOURCE
        CONFIG_VERSION="2021-03-27"
        _POSIX_C_SOURCE=200809L
        _WINDOWS
    )

    # Link required libraries
    target_link_libraries(QuickJSTest PRIVATE
        ws2_32
        Threads::Threads  # This links pthread on MinGW
    )
endif()

# Additional definitions
target_compile_definitions(QuickJSTest PRIVATE JS_STRICT_NAN_BOXING)
